package com.ynkbny.tasks;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ynkbny.aspect.TaskOperationLog;
import com.ynkbny.domain.dto.TEpTotalEnergyDTO;
import com.ynkbny.domain.dto.TEpUploadTimeDTO;
import com.ynkbny.service.BaseJob;
import com.ynkbny.service.TEpTotalEnergyService;
import com.ynkbny.service.TEpUploadTimeService;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Time;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author YY
 * @Date 2023/7/24 11:59
 */
@Component
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@ConditionalOnProperty(name = "schedule.enabled", havingValue = "false")
public class UploadDataEnergyToDay implements BaseJob {

    private static final Logger log = LoggerFactory.getLogger(UploadDataEnergyToDay.class);

    @Resource
    private TEpTotalEnergyService totalEnergyService;

    @Resource
    private TEpUploadTimeService timeService;

    /**
     * 自动上报数据
     */
    @Override
    @TaskOperationLog(description = "自动上报数据")
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("自动上报开始执行");
        //获取当前时间可以传输数据集的企业统一信用代码
        List<String> enterpriseCodeList = getUploadTimeForEnterpriseCode();
        if (enterpriseCodeList.size() == 0){
            log.info("当前时间没有可以上报的企业");
            return;
        }

        LambdaQueryWrapper<TEpTotalEnergyDTO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(TEpTotalEnergyDTO::getEnterpriseCode,enterpriseCodeList)
                //数据采集频率等于2
//                .eq(TEpTotalEnergyDTO::getStatType,"2")
                //端记录索引 为空
                .eq(TEpTotalEnergyDTO::getDataIndex,"")
                //连续错误次数 小于3 或为空（可以错三次）
                .and(wrapper -> wrapper.lt(TEpTotalEnergyDTO::getErrorNums, "3").or().isNull(TEpTotalEnergyDTO::getErrorNums))
                //上传数据 不为负数
                .notLike(TEpTotalEnergyDTO::getDataValue,"-")
                .last(" limit 100");
        List<TEpTotalEnergyDTO> list = totalEnergyService.list(lambdaQueryWrapper);
        log.info("查询到待上传数据{}条", list.size());

        // 数据上报 V2
        try {
            totalEnergyService.upLoadData(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前时间可以上传的企业统一信用代码
     * @return 企业统一信用代码集合
     */
    private List<String> getUploadTimeForEnterpriseCode(){
        log.info("获取当前时间可以上传的企业统一信用代码");
        //获取当前时间
        DateTime dateTime = new DateTime();
        Time nowTime = new Time(dateTime.getTime());
        //构造查询条件
        LambdaQueryWrapper<TEpUploadTimeDTO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //开始时间小于等于 当前时间
        lambdaQueryWrapper.le(TEpUploadTimeDTO::getStartTime,nowTime)
                //结束时间大于 当前时间
                .gt(TEpUploadTimeDTO::getEndTime,nowTime)
                //token不为空
                .isNotNull(TEpUploadTimeDTO::getToken);
        List<TEpUploadTimeDTO> list = timeService.list(lambdaQueryWrapper);
        List<String> enterpriseCodeList = list.stream()
                .map(TEpUploadTimeDTO::getEnterpriseCode)
                .collect(Collectors.toList());
        return enterpriseCodeList;
    }
}
